# Haxe skeleton for Bison

# Copyright (C) 2007, 2008, 2009, 2010 Free Software Foundation, Inc.

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# Haxe language support for Bison

# Copyright (C) 2007, 2008, 2009, 2010 Free Software Foundation, Inc.

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Haxe modifications by Hugh Sanderson - these mods are public domain, not GPL.
#


# b4_comment(TEXT)
# ----------------
m4_define([b4_comment], [/* m4_bpatsubst([$1], [
], [
   ])  */])


# b4_list2(LIST1, LIST2)
# --------------------------
# Join two lists with a comma if necessary.
m4_define([b4_list2],
	  [$1[]m4_ifval(m4_quote($1), [m4_ifval(m4_quote($2), [[, ]])])[]$2])


# b4_percent_define_get3(DEF, PRE, POST, NOT)
# -------------------------------------------
# Expand to the value of DEF surrounded by PRE and POST if it's %define'ed,
# otherwise NOT.
m4_define([b4_percent_define_get3],
	  [m4_ifval(m4_quote(b4_percent_define_get([$1])),
		[$2[]b4_percent_define_get([$1])[]$3], [$4])])



# b4_flag_value(BOOLEAN-FLAG)
# ---------------------------
m4_define([b4_flag_value], [b4_flag_if([$1], [true], [false])])


# b4_public_if(TRUE, FALSE)
# -------------------------
b4_percent_define_default([[public]], [[false]])
m4_define([b4_public_if],
[b4_percent_define_flag_if([public], [$1], [$2])])


# b4_abstract_if(TRUE, FALSE)
# ---------------------------
b4_percent_define_default([[abstract]], [[false]])
m4_define([b4_abstract_if],
[b4_percent_define_flag_if([abstract], [$1], [$2])])


# b4_final_if(TRUE, FALSE)
# ---------------------------
b4_percent_define_default([[final]], [[false]])
m4_define([b4_final_if],
[b4_percent_define_flag_if([final], [$1], [$2])])


# b4_strictfp_if(TRUE, FALSE)
# ---------------------------
b4_percent_define_default([[strictfp]], [[false]])
m4_define([b4_strictfp_if],
[b4_percent_define_flag_if([strictfp], [$1], [$2])])


# b4_lexer_if(TRUE, FALSE)
# ------------------------
m4_define([b4_lexer_if],
[b4_percent_code_ifdef([[lexer]], [$1], [$2])])


# b4_identification
# -----------------
m4_define([b4_identification],
[  /** Version number for the Bison executable that generated this parser.  */
  public static inline var bisonVersion = "b4_version";

  /** Name of the skeleton that generated this parser.  */
  public static inline var bisonSkeleton = b4_skeleton;
])


## ------------ ##
## Data types.  ##
## ------------ ##

# b4_int_type(MIN, MAX)
# ---------------------
# Return the smallest int type able to handle numbers ranging from
# MIN to MAX (included).
m4_define([b4_int_type],
[m4_if(b4_ints_in($@,   [-128],   [127]), [1], [byte],
       b4_ints_in($@, [-32768], [32767]), [1], [short],
					       [int])])

# b4_int_type_for(NAME)
# ---------------------
# Return the smallest int type able to handle numbers ranging from
# `NAME_min' to `NAME_max' (included).
m4_define([b4_int_type_for],
[b4_int_type($1_min, $1_max)])

# b4_null
# -------
m4_define([b4_null], [null])


## ------------------------- ##
## Assigning token numbers.  ##
## ------------------------- ##

# b4_token_enum(TOKEN-NAME, TOKEN-NUMBER)
# ---------------------------------------
# Output the definition of this token as an enum.
m4_define([b4_token_enum],
[  /** Token number, to be returned by the scanner.  */
  public static inline var $1 = $2;
])


# b4_token_enums(LIST-OF-PAIRS-TOKEN-NAME-TOKEN-NUMBER)
# -----------------------------------------------------
# Output the definition of the tokens (if there are) as enums.
m4_define([b4_token_enums],
[m4_if([$#$1], [1], [],
[/* Tokens.  */
m4_map([b4_token_enum], [$@])])
])

# b4-case(ID, CODE)
# -----------------
m4_define([b4_case], [  case $1:
    $2;
    ])


## ---------------- ##
## Default values.  ##
## ---------------- ##

m4_define([b4_yystype], [b4_percent_define_get([[stype]])])
b4_percent_define_default([[stype]], [[Object]])])

# %name-prefix
m4_define_default([b4_prefix], [[YY]])

b4_percent_define_default([[parser_class_name]], [b4_prefix[]Parser])])
m4_define([b4_parser_class_name], [b4_percent_define_get([[parser_class_name]])])

b4_percent_define_default([[lex_throws]], [[java.io.IOException]])])
m4_define([b4_lex_throws], [b4_percent_define_get([[lex_throws]])])

b4_percent_define_default([[throws]], [])])
m4_define([b4_throws], [b4_percent_define_get([[throws]])])

b4_percent_define_default([[location_type]], [Location])])
m4_define([b4_location_type], [b4_percent_define_get([[location_type]])])

b4_percent_define_default([[position_type]], [Position])])
m4_define([b4_position_type], [b4_percent_define_get([[position_type]])])


## ----------------- ##
## Semantic Values.  ##
## ----------------- ##


# b4_lhs_value([TYPE])
# --------------------
# Expansion of $<TYPE>$.
m4_define([b4_lhs_value], [yyval])


# b4_rhs_value(RULE-LENGTH, NUM, [TYPE])
# --------------------------------------
# Expansion of $<TYPE>NUM, where the current rule has RULE-LENGTH
# symbols on RHS.
#
# In this simple implementation, %token and %type have class names
# between the angle brackets.
m4_define([b4_rhs_value],
[(m4_ifval($3, [($3)])[](yystack.valueAt ($1-($2))))])

# b4_lhs_location()
# -----------------
# Expansion of @$.
m4_define([b4_lhs_location],
[(yyloc)])


# b4_rhs_location(RULE-LENGTH, NUM)
# ---------------------------------
# Expansion of @NUM, where the current rule has RULE-LENGTH symbols
# on RHS.
m4_define([b4_rhs_location],
[yystack.locationAt ($1-($2))])


# b4_lex_param
# b4_parse_param
# --------------
# If defined, b4_lex_param arrives double quoted, but below we prefer
# it to be single quoted.  Same for b4_parse_param.

# TODO: should be in bison.m4
m4_define_default([b4_lex_param], [[]]))
m4_define([b4_lex_param], b4_lex_param))
m4_define([b4_parse_param], b4_parse_param))

# b4_lex_param_decl
# -------------------
# Extra formal arguments of the constructor.
m4_define([b4_lex_param_decl],
[m4_ifset([b4_lex_param],
          [b4_remove_comma([$1],
			   b4_param_decls(b4_lex_param))],
	  [$1])])

m4_define([b4_param_decls],
	  [m4_map([b4_param_decl], [$@])])
m4_define([b4_param_decl], [, $1])

m4_define([b4_remove_comma], [m4_ifval(m4_quote($1), [$1, ], [])m4_shift2($@)])



# b4_parse_param_decl
# -------------------
# Extra formal arguments of the constructor.
m4_define([b4_parse_param_decl],
[m4_ifset([b4_parse_param],
          [b4_remove_comma([$1],
			   b4_param_decls(b4_parse_param))],
	  [$1])])



# b4_lex_param_call
# -------------------
# Delegating the lexer parameters to the lexer constructor.
m4_define([b4_lex_param_call],
          [m4_ifset([b4_lex_param],
	            [b4_remove_comma([$1],
				     b4_param_calls(b4_lex_param))],
	            [$1])])
m4_define([b4_param_calls],
	  [m4_map([b4_param_call], [$@])])
m4_define([b4_param_call], [, $2])



# b4_parse_param_cons
# -------------------
# Extra initialisations of the constructor.
m4_define([b4_parse_param_cons],
          [m4_ifset([b4_parse_param],
		    [b4_constructor_calls(b4_parse_param)])])

m4_define([b4_constructor_calls],
	  [m4_map([b4_constructor_call], [$@])])
m4_define([b4_constructor_call],
	  [this.m4_bpatsubst($1,[:.*],[ ]) = m4_bpatsubst($1,[:.*],[ ]);
	  ])



# b4_parse_param_vars
# -------------------
# Extra instance variables.
m4_define([b4_parse_param_vars],
          [m4_ifset([b4_parse_param],
		    [
    /* User arguments.  */
b4_var_decls(b4_parse_param)])])

m4_define([b4_var_decls],
	  [m4_map_sep([b4_var_decl], [
], [$@])])
m4_define([b4_var_decl],
	  [    var $1;])



# b4_maybe_throws(THROWS)
# -----------------------
# Expand to either an empty string or "throws THROWS".
m4_define([b4_maybe_throws],
	  [m4_ifval($1, [throws $1])])











b4_defines_if([b4_fatal([%s: %%defines does not make sense in Haxe], [b4_skeleton])])
m4_ifval(m4_defn([b4_symbol_destructors]),
        [b4_fatal([%s: %%destructor does not make sense in Haxe], [b4_skeleton])],
        [])

m4_divert_push(0)dnl
@output(b4_parser_file_name@)@
b4_copyright([Skeleton implementation for Bison LALR(1) parsers in Haxe],
             [2007, 2008, 2009, 2010])

b4_percent_define_ifdef([package], [package b4_percent_define_get([package]);
])[/* First part of user declarations.  */
]b4_pre_prologue
b4_percent_code_get([[imports]])
[/**
 * A Bison parser, automatically generated from <tt>]m4_bpatsubst(b4_file_name, [^"\(.*\)"$], [\1])[</tt>.
 *
 * @@author LALR (1) parser skeleton written by Paolo Bonzini.
 */



  /**
   * Communication interface between the scanner and the Bison-generated
   * parser <tt>]b4_parser_class_name[</tt>.
   */
interface Lexer {
    ]b4_locations_if([[
     /**
     * Method to retrieve the beginning position of the last scanned token.
     * @@return the position at which the last scanned token starts.  */
     public function getStartPos():]b4_position_type[;

    /**
     * Method to retrieve the ending position of the last scanned token.
     * @@return the first position beyond the last scanned token.  */
     public function getEndPos():]b4_position_type[;
    ]])[

    /**
     * Method to retrieve the semantic value of the last scanned token.
     * @@return the semantic value of the last scanned token.  */
    public function getLVal () : ]b4_yystype[;

    /**
     * Entry point for the scanner.  Returns the token identifier corresponding
     * to the next token and prepares to return the semantic value
     * ]b4_locations_if([and beginning/ending positions ])[of the token.
     * @@return the token identifier corresponding to the next token. */
    public function yylex () : Int;

    /**
     * Entry point for error reporting.  Emits an error
     * ]b4_locations_if([referring to the given location ])[in a user-defined way.
     *
     * ]b4_locations_if([[@@param loc The location of the element to which the
     *                error message is related]])[
     * @@param s The string for the error message.  */
     public function yyerror(message:String, ?location:Dynamic) : Void;
  }

  class YYStackVal
  {
     public function new()
     {
     }

     public var state:Int;
     public var value:]b4_yystype[;

     ]b4_locations_if([[

     public var line0:Int;
     public var col0:Int;
     public var file0:String;

     public var line1:Int;
     public var col1:Int;
     public var file1:String;

     ]])[
  }


  class YYStack {
    var stack:Array<YYStackVal>;

    public var height:Int;

    public function new()
    {
       height = 0;
       stack= new Array<YYStackVal>();
    }

    public function push(inState:Int, inValue:]b4_yystype dnl
			    b4_locations_if([, loc:]b4_location_type[ ])[) : Void
    {
      if (stack.length <= height)
         stack.push(new YYStackVal());

      var val = stack[height++];
      val.state = inState;
      val.value = inValue;

      ]b4_locations_if([[

      if (loc.begin!=null)
      {
      val.line0 = loc.begin.line;
      val.col0 = loc.begin.col;
      val.file0 = loc.begin.file;
      }

      if (loc.end!=null)
      {
      val.line1 = loc.end.line;
      val.col1 = loc.end.col;
      val.file1 = loc.end.file;
      }

      ]])[
    }

    public function pop() : Void {
      height--;
    }

    public function popN(num:Int):Void {
      height -= num;
    }

    public function stateAt(i:Int): Int {
      return stack[height-1-i].state;
    }

    public function itemAt(i:Int)  {
      return stack[height-1-i];
    }


    ]b4_locations_if([[public function locationAt(i:Int): ]b4_location_type[ {
      var val = stack[height-1-i];
      return new Location( new Position(val.line0,val.col0,val.file0),
                           new Position(val.line1,val.col1,val.file1) );
    }
    ]])[

    public function valueAt(i:Int) : ]b4_yystype[ {
      return stack[height-1-i].value;
    }

    // Print the state stack on the debug stream.
    public function print( out:haxe.io.Output) : Void
    {
      out.writeString("Stack now");

      for(i in 0...height)
	      out.writeString(" " + stack[i]);
      out.writeString("\n");
    }
  }



]b4_locations_if([[

  /**
   * A class defining a pair of positions.  Positions, defined by the
   * <code>]b4_position_type[</code> class, denote a point in the input.
   * Locations represent a part of the input through the beginning
   * and ending positions.  */
  class ]b4_location_type[ {
    /** The first, inclusive, position in the range.  */
    public var begin: ]b4_position_type[;

    /** The first position beyond the range.  */
    public var end : ]b4_position_type[;

    /**
     * Create a <code>]b4_location_type[</code> from the endpoints of the range.
     * @@param begin The first position included in the range.
     * @@param end   The first position beyond the range.  */
    public function new(begin:]b4_position_type[, end: ]b4_position_type[) {
      this.begin = begin;
      this.end = end;
    }

    /**
     * Create a <code>]b4_location_type[</code> denoting an empty range located at
     * a given point.
     * @@param loc The position at which the range is anchored.  */
    public static function create(loc:]b4_position_type[) : ]b4_location_type[  {
      return new Location(loc,loc);
    }


    /**
     * Print a representation of the location.  For this to be correct,
     * <code>]b4_position_type[</code> should override the <code>equals</code>
     * method.  */
    public function toString ():String {
      if (begin==null)
         return "nowhere";
      else
         return begin.rangeString(end);
    }
  }

]])
[







]b4_public_if([public ])dnl
b4_abstract_if([abstract ])dnl
b4_final_if([final ])dnl
b4_strictfp_if([strictfp ])dnl
[class ]b4_parser_class_name[]dnl
b4_percent_define_get3([extends], [ extends ])dnl
b4_percent_define_get3([implements], [ implements ])[
{
  ]b4_identification[

  /** True if verbose error messages are enabled.  */
  public static var errorVerbose = ]b4_flag_value([error_verbose]);
[  /** Token returned by the scanner to signal the end of its input.  */
  public static inline var EOF = 0;]

b4_token_enums(b4_tokens)

  b4_locations_if([[
  function yylloc_get(outLoc:Location, rhs:YYStack , n:Int) : Void
  {
    if (n > 0)
    {
      var val0 = rhs.itemAt(1);
      var valN = rhs.itemAt(n);
      outLoc.begin.line = val0.line0;
      outLoc.begin.col = val0.col0;
      outLoc.begin.file = val0.file0;
      outLoc.end.line = valN.line1;
      outLoc.end.col = valN.col1;
      outLoc.end.file = valN.file1;
    }
    else
    {
      var val = rhs.itemAt(0);
      outLoc.begin.line = val.line0;
      outLoc.begin.col = val.col0;
      outLoc.begin.file = val.file0;
      outLoc.end.line = val.line1;
      outLoc.end.col = val.col1;
      outLoc.end.file = val.file1;
    }
  }]])
  [/** The object doing lexical analysis for us.  */
  var yylexer:Lexer;
  ]
  b4_parse_param_vars

  var yyDebugStream : haxe.io.Output;
  var yydebug:Int;


  /**
   * Instantiates the Bison-generated parser.
   * @@param yylexer The scanner that will supply tokens to the parser.
   */
   [public function new (]b4_parse_param_decl([[yylexer:Lexer]])[) {
    this.yylexer = yylexer;
    yydebug = 0;
    yyDebugStream = new haxe.io.BytesOutput();
    yyerrstatus_ = 0;
    initParse();

    ]b4_parse_param_cons[
  }


  /**
   * Return the <tt>PrintStream</tt> on which the debugging output is
   * printed.
   */
  public function getDebugStream() : haxe.io.Output
  {
     return yyDebugStream;
  }

  /**
   * Set the <tt>PrintStream</tt> on which the debug output is printed.
   * @@param s The stream that is used for debugging output.
   */
  public function setDebugStream(s:haxe.io.Output) : Void { yyDebugStream = s; }

  /**
   * Answer the verbosity of the debugging output; 0 means that all kinds of
   * output from the parser are suppressed.
   */
  public function getDebugLevel():Int { return yydebug; }

  /**
   * Set the verbosity of the debugging output; 0 means that all kinds of
   * output from the parser are suppressed.
   * @@param level The verbosity level for debugging output.
   */
  public function setDebugLevel(level:Int) : Void { yydebug = level; }

  private function yylex ():Int {
    return yylexer.yylex ();
  }

  public dynamic function errorFunction(s:String,info:Dynamic) : Int
  {
     if (yylexer!=null)
        yylexer.yyerror(s,info);
     return YYERROR;
  }

  public dynamic function output(s:String) : Void
  {
     trace(s);
  }


  function yyerror(s:String,?info:Dynamic) : Int { return errorFunction(s,info); }

  function yycdebug (s:String):Void {
    if (yydebug > 0)
      yyDebugStream.writeString(s + "\n");
  }

  public static inline var YYLEX_STARVED = -99;

  /**
   * Returned by a Bison action in order to stop the parsing process and
   * return success (<tt>true</tt>).  */
  public static inline var YYACCEPT = 0;

  /**
   * Returned by a Bison action in order to stop the parsing process and
   * return failure (<tt>false</tt>).  */
  public static inline var YYABORT = 1;

  /**
   * Returned by a Bison action in order to start error recovery without
   * printing an error message.  */
  public static inline var YYERROR = 2;

  /**
   * Returned by a Bison action in order to print an error message and start
   * error recovery.  Formally deprecated in Bison 2.4.2's NEWS entry, where
   * a plan to phase it out is discussed.  */
  public static inline var YYFAIL = 3;

  private static inline var YYNEWSTATE = 4;
  private static inline var YYDEFAULT = 5;
  private static inline var YYREDUCE = 6;
  private static inline var YYERRLAB1 = 7;
  private static inline var YYRETURN = 8;

  private var yyerrstatus_:Int;

  /**
   * Return whether error recovery is being done.  In this state, the parser
   * reads token until it reaches a known state, and then restarts normal
   * operation.  */
  public function recovering ()
  {
    return yyerrstatus_ == 0;
  }


  ]b4_locations_if([[
  public function getCurrentLocation() : ]b4_location_type[
  {
      return  yylexer!=null ?
                 new ]b4_location_type[(yylexer.getStartPos(),yylexer.getEndPos()) :
                 pendingLocation;
  }
  ]])[

  function yyaction(yyn:Int, yystack:YYStack, yylen:Int) : Int
  {
    var yyval : ]b4_yystype[ = null;
    ]b4_locations_if([ yylloc_get(yyTmpLoc,yystack, yylen);])[

    /* If YYLEN is nonzero, implement the default value of the action:
       `$$ = $1'.  Otherwise, use the top of the stack.

       Otherwise, the following line sets YYVAL to garbage.
       This behavior is undocumented and Bison
       users should not rely upon it.  */
    if (yylen > 0)
      yyval = yystack.valueAt (yylen - 1);
    else
      yyval = yystack.valueAt (0);

    if (yydebug > 0)
       yy_reduce_print (yyn, yystack);

    switch (yyn)
      {
	]b4_user_actions[
	default:
      }

    if (yydebug > 0)
    yy_symbol_print ("-> $$ =", yyr1_[yyn], yyval]b4_locations_if([, yyTmpLoc])[);

    yystack.popN(yylen);
    yylen = 0;

    /* Shift the result of the reduction.  */
    yyn = yyr1_[yyn];
    var yystate:Int = yypgoto_[yyn - yyntokens_] + yystack.stateAt (0);
    if (0 <= yystate && yystate <= yylast_
	&& yycheck_[yystate] == yystack.stateAt (0))
      yystate = yytable_[yystate];
    else
      yystate = yydefgoto_[yyn - yyntokens_];

    yystack.push (yystate, yyval]b4_locations_if([, yyTmpLoc])[);
    return YYNEWSTATE;
  }

  /* Return YYSTR after stripping away unnecessary quotes and
     backslashes, so that it's suitable for yyerror.  The heuristic is
     that double-quoting is unnecessary unless the string contains an
     apostrophe, a comma, or backslash (other than backslash-backslash).
     YYSTR is taken from yytname.  */
  function yytnamerr_(yystr:String):String
  {
    if (yystr.charAt (0) == '"')
    {
       // Just return string for now...
       return yystr;
    }
    else if (yystr == "$end")
      return "end of input";

    return yystr;
  }

  /*--------------------------------.
  | Print this symbol on YYOUTPUT.  |
  `--------------------------------*/

  function yy_symbol_print(s:String, yytype:Int, yyvaluep:]b4_yystype dnl
				 b4_locations_if([, yylocationp:b4_location_type ])[)
  {
    if (yydebug > 0)
      yycdebug (s + (yytype < yyntokens_ ? " token " : " nterm ")
	      + yytname_[yytype] + " ("]b4_locations_if([
	      + yylocationp + ": "])[
	      + yyvaluep + ")");
  }

  /**
   * Parse input from the scanner that was specified at object construction
   * time.  Return whether the end of the input was reached successfully.
   *
   * @@return <tt>true</tt> if the parsing succeeds.  Note that this does not
   *          imply that there were no syntax errors.
   */


    /// Lookahead and lookahead in internal form.
    var yychar:Int;
    var yytoken:Int;

    /* State.  */
    var yyn:Int;
    var yylen:Int;
    var yystate:Int;

    var yystack:YYStack;

    /* Error handling.  */
    var yynerrs_:Int;
    ]b4_locations_if([/// The location where the error started.
     var yyerrloc:]b4_location_type[;

    /// ]b4_location_type[ of the lookahead.
    var yylloc:]b4_location_type[;
    var yyTmpLoc:]b4_location_type[;

    /// @@$.
    var yyloc :  ]b4_location_type[;])

    /// Semantic value of the lookahead.
    var yylval: b4_yystype[;

    var yyresult:Int;

    var label:Int;
 

  public function initParse()
  {
    /// Lookahead and lookahead in internal form.
    yychar = yyempty_;
    yytoken = 0;

    /* State.  */
    yyn = 0;
    yylen = 0;
    yystate = 0;

    yystack = new YYStack ();

    /* Error handling.  */
    yynerrs_ = 0;
    ]b4_locations_if([/// The location where the error started.
     yyerrloc= null;

    /// ]b4_location_type[ of the lookahead.
    yylloc = new ]b4_location_type[ (new Position(0,0,""), new Position(0,0,""));

    /// @@$.
    yyloc  = new ]b4_location_type[ (new Position(0,0,""), new Position(0,0,""));
    yyTmpLoc  = new ]b4_location_type[ (new Position(0,0,""), new Position(0,0,""));
    ])

    /// Semantic value of the lookahead.
    yylval = null;

    yyresult = 0;

    if (yydebug>0)
       yycdebug ("Starting parse\n");
    yyerrstatus_ = 0;

m4_ifdef([b4_initial_action], [
m4_pushdef([b4_at_dollar],     [yylloc])dnl
m4_pushdef([b4_dollar_dollar], [yylval])dnl
    /* User initialization code.  */
    b4_user_initial_action
m4_popdef([b4_dollar_dollar])dnl
m4_popdef([b4_at_dollar])])dnl

  [  /* Initialize the stack.  */
    yystack.push (yystate, yylval]b4_locations_if([, yylloc])[);

    label = YYNEWSTATE;
  }

  public static inline var PARSE_FAIL = 0;
  public static inline var PARSE_COMPLETE = 1;
  public static inline var PARSE_CONTINUE = 2;

  var parseFinished:Bool;
  var pendingToken:Int;
  var pendingLVal:Dynamic;
  ]b4_locations_if([[ var pendingLocation : ]b4_location_type[; ]])[
   
  public function parseToken(token:Int, lval:Dynamic  ]b4_locations_if([[, loc:]b4_location_type[ ]])[ ) : Int
  {
     parseFinished = true;
     pendingToken = token;
     pendingLVal = lval;
     ]b4_locations_if([[ pendingLocation = loc; ]])[

     var result = parse();
     if (!parseFinished)
        return PARSE_CONTINUE;
      
     return result ? PARSE_COMPLETE : PARSE_FAIL;
  }


  public function parse() : Bool
  {
    var tokenRequired = false;

    while(true)
      switch (label)
      {
        /* New state.  Unlike in the C/C++ skeletons, the state is already
	   pushed when we come here.  */
      case YYNEWSTATE:
        if (yydebug > 0)
        {
          yycdebug ("Entering state " + yystate + "\n");
          yystack.print (yyDebugStream);
        }

        /* Accept?  */
        if (yystate == yyfinal_)
          return true;

        /* Take a decision.  First try without lookahead.  */
        yyn = yypact_[yystate];
        if (yyn == yypact_ninf_)
          {
            label = YYDEFAULT;
          }
        else
        {

        /* Read a lookahead token.  */
        if (yychar == yyempty_)
        {
          if (yydebug>0)
	          yycdebug ("Reading a token: ");
          if (yylexer==null)
          {
             if (tokenRequired)
             {
                parseFinished = false;
                return false;
             }
             else
             {
                yychar = pendingToken;
                ]b4_locations_if([[
                yylloc.begin.line = pendingLocation.begin.line; 
                yylloc.begin.col = pendingLocation.begin.col; 
                yylloc.begin.file = pendingLocation.begin.file; 
                yylloc.end.line = pendingLocation.end.line; 
                yylloc.end.col = pendingLocation.end.col; 
                yylloc.end.file = pendingLocation.end.file; 
                ]])[
                yylval = pendingLVal;
                tokenRequired = true;
             }
          }
          else
          {
	          yychar = yylex ();]
             // TODO - fill yyloc
             b4_locations_if([[
               var start = yylexer.getStartPos();
               yylloc.begin.line = start.line;
               yylloc.begin.col = start.col;
               yylloc.begin.file = start.file;
               var end = yylexer.getEndPos();
               yylloc.end.line = end.line;
               yylloc.end.col = end.col;
               yylloc.end.file = end.file;
             ]])
             yylval = yylexer.getLVal ();[
          }
        }

        /* Convert token to internal form.  */
        if (yychar <= EOF)
          {
	    yychar = yytoken = EOF;
       if (yydebug>0)
	    yycdebug ("Now at end of input.\n");
          }
        else
          {
	    yytoken = yytranslate_ (yychar);
	    yy_symbol_print ("Next token is", yytoken,
			     yylval]b4_locations_if([, yylloc])[);
          }

        /* If the proper action on seeing token YYTOKEN is to reduce or to
           detect an error, take that action.  */
        yyn += yytoken;
        if (yyn < 0 || yylast_ < yyn || yycheck_[yyn] != yytoken)
          label = YYDEFAULT;

        /* <= 0 means reduce or error.  */
        else if ((yyn = yytable_[yyn]) <= 0)
          {
	    if (yyn == 0 || yyn == yytable_ninf_)
	      label = YYFAIL;
	    else
	      {
	        yyn = -yyn;
	        label = YYREDUCE;
	      }
          }

        else
          {
            /* Shift the lookahead token.  */
	    yy_symbol_print ("Shifting", yytoken,
			     yylval]b4_locations_if([, yylloc])[);

            /* Discard the token being shifted.  */
            yychar = yyempty_;

            /* Count tokens shifted since error; after three, turn off error
               status.  */
            if (yyerrstatus_ > 0)
              --yyerrstatus_;

            yystate = yyn;
            yystack.push (yystate, yylval]b4_locations_if([, yylloc])[);
            label = YYNEWSTATE;
          }
        }

      /*-----------------------------------------------------------.
      | yydefault -- do the default action for the current state.  |
      `-----------------------------------------------------------*/
      case YYDEFAULT:
        yyn = yydefact_[yystate];
        if (yyn == 0)
          label = YYFAIL;
        else
          label = YYREDUCE;

      /*-----------------------------.
      | yyreduce -- Do a reduction.  |
      `-----------------------------*/
      case YYREDUCE:
        yylen = yyr2_[yyn];
        label = yyaction (yyn, yystack, yylen);
	yystate = yystack.stateAt (0);

      /*------------------------------------.
      | yyerrlab -- here on detecting error |
      `------------------------------------*/
      case YYFAIL:
        /* If not already recovering from an error, report this error.  */
        if (yyerrstatus_ == 0)
          {
	    ++yynerrs_;
	    yyerror(yysyntax_error(yystate, yytoken) ]b4_locations_if([,yylloc ])[);
          }

        ]b4_locations_if([yyerrloc = yylloc;])[
        if (yyerrstatus_ == 3)
          {
	    /* If just tried and failed to reuse lookahead token after an
	     error, discard it.  */

	    if (yychar <= EOF)
	      {
	      /* Return failure if at end of input.  */
	      if (yychar == EOF)
	        return false;
	      }
	    else
	      yychar = yyempty_;
          }

        /* Else will try to reuse lookahead token after shifting the error
           token.  */
        label = YYERRLAB1;

      /*---------------------------------------------------.
      | errorlab -- error raised explicitly by YYERROR.  |
      `---------------------------------------------------*/
      case YYERROR:

        ]b4_locations_if([yyerrloc = yystack.locationAt (yylen - 1);])[
        /* Do not reclaim the symbols of the rule which action triggered
           this YYERROR.  */
        yystack.popN(yylen);
        yylen = 0;
        yystate = yystack.stateAt (0);
        label = YYERRLAB1;

      /*-------------------------------------------------------------.
      | yyerrlab1 -- common code for both syntax error and YYERROR.  |
      `-------------------------------------------------------------*/
      case YYERRLAB1:
        yyerrstatus_ = 3;	/* Each real token shifted decrements this.  */

        while(true)
          {
	    yyn = yypact_[yystate];
	    if (yyn != yypact_ninf_)
	      {
	        yyn += yyterror_;
	        if (0 <= yyn && yyn <= yylast_ && yycheck_[yyn] == yyterror_)
	          {
	            yyn = yytable_[yyn];
	            if (0 < yyn)
		      break;
	          }
	      }

	    /* Pop the current state because it cannot handle the error token.  */
	    if (yystack.height == 1)
	      return false;

	    ]b4_locations_if([yyerrloc = yystack.locationAt (0);])[
	    yystack.pop ();
	    yystate = yystack.stateAt (0);
	    if (yydebug > 0)
	      yystack.print (yyDebugStream);
          }

	     ]b4_locations_if([
	     /* Muck with the stack to setup for yylloc.  */
        yystack.push (0, null, yylloc);
        yystack.push (0, null, yyerrloc);
        yylloc_get(yyloc, yystack, 2);
        yystack.popN(2);])[

        /* Shift the error token.  */
        yy_symbol_print ("Shifting", yystos_[yyn],
			 yylval]b4_locations_if([, yyloc])[);

        yystate = yyn;
        yystack.push (yyn, yylval]b4_locations_if([, yylloc])[);
        label = YYNEWSTATE;

        /* Accept.  */
      case YYACCEPT:
        return true;

        /* Abort.  */
      case YYABORT:
        return false;
      }
      throw "Should not get here";
     return true;
  }

  // Generate an error message.
  function yysyntax_error (yystate:Int, tok:Int) : String
  {
    if (errorVerbose)
      {
        var yyn = yypact_[yystate];
        if (yypact_ninf_ < yyn && yyn <= yylast_)
          {
	    var res : String = "";

	    /* Start YYX at -YYN if negative to avoid negative indexes in
	       YYCHECK.  */
	    var yyxbegin:Int = yyn < 0 ? -yyn : 0;

	    /* Stay within bounds of both yycheck and yytname.  */
	    var yychecklim:Int = yylast_ - yyn + 1;
	    var yyxend:Int = yychecklim < yyntokens_ ? yychecklim : yyntokens_;
	    var count:Int = 0;
	    for (x in yyxbegin ... yyxend)
	      if (yycheck_[x + yyn] == x && x != yyterror_)
	        ++count;

	    // FIXME: This method of building the message is not compatible
	    // with internationalization.
	    res = "syntax error, unexpected ";
	    res += (yytnamerr_ (yytname_[tok]));
	    if (count < 5)
	      {
	        count = 0;
	        for (x in yyxbegin ... yyxend)
	          if (yycheck_[x + yyn] == x && x != yyterror_)
		    {
		      res += (count++ == 0 ? ", expecting " : " or ");
		      res += (yytnamerr_ (yytname_[x]));
		    }
	      }
	    return res;
          }
      }

    return "syntax error";
  }


  /* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing
     STATE-NUM.  */
  private static inline var yypact_ninf_ = ]b4_pact_ninf[;
  private static var yypact_ =
  [//]
    ]b4_pact[
  ]][;

  /* YYDEFACT[S] -- default rule to reduce with in state S when YYTABLE
     doesn't specify something else to do.  Zero means the default is an
     error.  */
  private static var yydefact_ =
  [//]
    ]b4_defact[
  ]][;

  /* YYPGOTO[NTERM-NUM].  */
  private static var yypgoto_ =
  [//]
    ]b4_pgoto[
  ]][;

  /* YYDEFGOTO[NTERM-NUM].  */
  private static var yydefgoto_ =
  [//]
    ]b4_defgoto[
  ]][;

  /* YYTABLE[YYPACT[STATE-NUM]].  What to do in state STATE-NUM.  If
     positive, shift that token.  If negative, reduce the rule which
     number is the opposite.  If zero, do what YYDEFACT says.  */
  private static inline var yytable_ninf_ = ]b4_table_ninf[;
  private static var yytable_ =
  [//]
    ]b4_table[
  ]][;

  /* YYCHECK.  */
  private static var yycheck_ =
  [//]
    ]b4_check[
  ]][;

  /* STOS_[STATE-NUM] -- The (internal number of the) accessing
     symbol of state STATE-NUM.  */
  private static var yystos_ =
  [//]
    ]b4_stos[
  ]][;

  /* TOKEN_NUMBER_[YYLEX-NUM] -- Internal symbol number corresponding
     to YYLEX-NUM.  */
  private static var yytoken_number_ =
  [//]
    ]b4_toknum[
  ]][;

  /* YYR1[YYN] -- Symbol number of symbol that rule YYN derives.  */
  private static var yyr1_ =
  [//]
    ]b4_r1[
  ]][;

  /* YYR2[YYN] -- Number of symbols composing right hand side of rule YYN.  */
  private static var yyr2_ =
  [//]
    ]b4_r2[
  ]][;

  /* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM.
     First, the terminals, then, starting at \a yyntokens_, nonterminals.  */
  private static var yytname_:Array<String> =
  [//]
    ]b4_tname[
  ]][;

  /* YYRHS -- A `-1'-separated list of the rules' RHS.  */
  private static var yyrhs_ =
  [//]
    ]b4_rhs[
  ]][;

  /* YYPRHS[YYN] -- Index of the first RHS symbol of rule number YYN in
     YYRHS.  */
  private static var yyprhs_ =
  [//]
    ]b4_prhs[
  ]][;

  /* YYRLINE[YYN] -- Source line where rule number YYN was defined.  */
  private static var yyrline_ =
  [//]
    ]b4_rline[
  ]][;

  // Report on the debug stream that the rule yyrule is going to be reduced.
  private function yy_reduce_print(yyrule:Int, yystack:YYStack) : Void
  {

    var yylno:Int = yyrline_[yyrule];
    var yynrhs:Int = yyr2_[yyrule];
    /* Print the symbols being reduced, and their result.  */
    yycdebug ("Reducing stack by rule " + (yyrule - 1)
	      + " (line " + yylno + "), ");

    /* The symbols being reduced.  */
    for ( yyi in 0...yynrhs)
      yy_symbol_print ("   $" + (yyi + 1) + " =",
		       yyrhs_[yyprhs_[yyrule] + yyi],
		       ]b4_rhs_value(yynrhs, yyi + 1)b4_locations_if([,
		       b4_rhs_location(yynrhs, yyi + 1)])[);
  }

  /* YYTRANSLATE(YYLEX) -- Bison symbol number corresponding to YYLEX.  */
  private static var yytranslate_table_ =
  [//]
    ]b4_translate[
  ]][;

  static function yytranslate_(t:Int) : Int
  {
    if (t >= 0 && t <= yyuser_token_number_max_)
      return yytranslate_table_[t];
    else
      return yyundef_token_;
  }

  private static inline var yylast_ = ]b4_last[;
  private static inline var yynnts_ = ]b4_nterms_number[;
  private static inline var yyempty_ = -2;
  private static inline var yyfinal_ = ]b4_final_state_number[;
  private static inline var yyterror_ = 1;
  private static inline var yyerrcode_ = 256;
  private static inline var yyntokens_ = ]b4_tokens_number[;

  private static inline var yyuser_token_number_max_ = ]b4_user_token_number_max[;
  private static inline var yyundef_token_ = ]b4_undef_token_number[;

]/* User implementation code.  */
b4_percent_code_get[]dnl

}

b4_epilogue
m4_divert_pop(0)dnl
